package cn.heyige.backend.entity;

import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;

import java.time.LocalDateTime;

@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("user_quota")
public class UserQuotaDO {
    
    @TableId(type = IdType.AUTO)
    private Integer id;
    
    @TableField("user_id")
    private Integer userId;
    
    @TableField("total_quota")
    private Integer totalQuota = 0;
    
    @TableField("used_quota")
    private Integer usedQuota = 0;
    
    @TableField("free_quota")
    private Integer freeQuota = 5;
    
    @TableField(value = "last_reset_date", fill = FieldFill.INSERT)
    private LocalDateTime lastResetDate;
    
    @TableField("last_used_time")
    private LocalDateTime lastUsedTime;

    @TableField(value = "create_time", fill = FieldFill.INSERT)
    private LocalDateTime createTime;

    @TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
    private LocalDateTime updateTime;
    
    /**
     * 获取剩余总次数
     */
    public Integer getRemainingQuota() {
        return (totalQuota - usedQuota) + freeQuota;
    }
    
    /**
     * 检查是否有可用次数
     */
    public boolean hasAvailableQuota() {
        return getRemainingQuota() > 0;
    }
    
    /**
     * 使用一次次数
     */
    public void useOneQuota() {
        if (freeQuota > 0) {
            freeQuota--;
        } else if (totalQuota > usedQuota) {
            usedQuota++;
        }
    }
    
    /**
     * 添加免费次数
     */
    public void addFreeQuota(Integer amount) {
        this.freeQuota += amount;
    }
    
    /**
     * 添加总次数
     */
    public void addTotalQuota(Integer amount) {
        this.totalQuota += amount;
    }
    
    /**
     * 重置每日免费次数
     */
    public void resetDailyFreeQuota(Integer dailyAmount) {
        this.freeQuota = dailyAmount;
        this.lastResetDate = LocalDateTime.now();
    }
    
    /**
     * 设置剩余配额
     */
    public void setRemainingQuota(Integer remainingQuota) {
        // 计算已使用的配额
        this.usedQuota = this.totalQuota - (remainingQuota - this.freeQuota);
        if (this.usedQuota < 0) {
            this.usedQuota = 0;
        }
    }
}